<template>
  <div class="user-register">
    <layout>
      <template v-slot:title>
        {{ $route.meta.title }}
      </template>
      <template v-slot:main>
        <div class="form">
          <div class="line">
            <span class="cubeic-person"></span>
            <input v-model="postForm.referrer" placeholder="推荐ID或手机号码" :disabled="+$store.getters['ExecUser/referrer'] > 0"/>
          </div>
          <div class="line">
            <span class="cubeic-phone"></span>
            <input placeholder="手机号码" v-model.trim="postForm.mobile"/>
          </div>
          <div class="line">
            <span class="cubeic-volume"></span>
            <input placeholder="验证码" v-model.trim="postForm.code"/>
            <div class="verify" @click="getVerify" :class="{'send': verifySend}">{{ verifyText }}</div>
          </div>
          <div class="line">
            <span class="cubeic-lock"></span>
            <input placeholder="设置密码" type="password" v-model="postForm.password"/>
          </div>
          <div class="line">
            <span class="cubeic-lock"></span>
            <input placeholder="确认密码" type="password" v-model="postForm.password2"/>
          </div>
          <div class="agreement">
            <span class="box"><cube-checkbox v-model="agreement" :option="{label: ''}" /></span>
            <span class="text">我已阅读并同意<i @click="$router.push('/user/agreement')">《注册协议》</i></span>
          </div>
          <div class="line">
            <button @click="submit">注 册</button>
          </div>
        </div>
        <ul class="footer">
          <li @click="$router.push('/user/login')">立即登录</li>
          <li @click="$router.push('/')">返回首页</li>
        </ul>
      </template>
    </layout>
    <loading :show="loading" />
  </div>
</template>

<script>
import Layout from './components/Layout'
import api from '@/api'
import base64 from '@/util/base64'
import Loading from '@/components/Loading'

const text = '获取验证码'

export default {
  name: 'UserRegister',
  components: {
    Layout,
    Loading
  },
  data() {
    return {
      postForm: {},
      verifyText: text,
      verifySend: false,
      agreement: true,
      needReferrer: false,
      loading: false
    }
  },
  methods: {
    /**
     * check form
     * @returns {boolean}
     * @private
     */
    _check() {
      const { mobile, password, password2, code, referrer } = this.postForm
      if (this.needReferrer && !referrer) {
        this.$createToast({
          type: 'error',
          txt: '请输入推荐人ID或者手机号码'
        }).show()
        return false
      }
      if (!mobile) {
        this.$createToast({
          type: 'error',
          txt: '请输入手机号码'
        }).show()
        return false
      }
      if (!password) {
        this.$createToast({
          type: 'error',
          txt: '请输入密码'
        }).show()
        return false
      }
      if (!/^1[3456789]\d{9}$/.test(mobile)) {
        this.$createToast({
          type: 'error',
          txt: '手机号码错误'
        }).show()
        return false
      }
      if (password.length < 6) {
        this.$createToast({
          type: 'error',
          txt: '密码长度不能小于6位'
        }).show()
        return false
      }
      if (password !== password2) {
        this.$createToast({
          type: 'error',
          txt: '两次密码不一致'
        }).show()
        return false
      }
      if (!code) {
        this.$createToast({
          type: 'error',
          txt: '请输入验证码'
        }).show()
        return false
      }
      return true
    },
    /**
     * timeout
     * @param timeout
     * @private
     */
    _timer(timeout) {
      setTimeout(() => {
        timeout--
        this.verifyText = `${timeout}秒后重新发送`
        if (timeout !== 0) {
          this._timer(timeout)
        } else {
          this.verifyText = text
          this.verifySend = false
        }
      }, 1000)
    },
    getVerify() {
      if (this.verifySend) {
        return false
      }
      if (!this.postForm.mobile) {
        this.$createToast({
          type: 'error',
          txt: '请输入手机号码'
        }).show()
        return false
      }
      if (!/^1[3456789]\d{9}$/.test(this.postForm.mobile)) {
        this.$createToast({
          type: 'error',
          txt: '手机号码错误'
        }).show()
        return false
      }
      // request api
      api.User.getVerify({ ...this.postForm }).then(response => {
        let { data } = response
        data = base64.parse(data)
        const msg = (data.code && `验证码是:${data.code}`) || response.message
        const time = (data.code && 5000) || 2000
        this.verifySend = true
        this._timer(data.timeout * 60)
        this.$createToast({
          type: 'txt',
          time: time,
          txt: msg
        }).show()
      })
    },
    _register() {
      this.loading = true
      api.User.register({ ...this.postForm }).then(() => {
        this.$createToast({
          type: 'correct',
          txt: '注册成功',
          time: 1000,
          onTimeout: () => {
            // this.$router.push('/user/login')
            // go to subscribe wx
            this.$router.push('/service/subscribe')
          }
        }).show()
      }).finally(() => {
        this.loading = false
      })
    },
    submit() {
      if (this._check()) {
        // check agreement
        if (!this.agreement) {
          this.$createToast({
            type: 'error',
            txt: '只有同意注册协议才能注册'
          }).show()
          return false
        }
        // check verify
        api.User.checkVerify({ ...this.postForm }).then(() => {
          this._register()
        })
      }
    }
  },
  created () {
    // referrer id
    // this.$store.dispatch('ExecUser/set_referrer', 10001)
    const referrer = this.$store.getters['ExecUser/referrer']
    if (referrer) {
      this.postForm.referrer = referrer
    }
    // check need referrer register
    api.User.needReferrer().then(response => {
      let { data } = response
      data = base64.parse(data)
      this.needReferrer = !!data
    })
  }
}
</script>

<style scoped lang="stylus">
.form
  padding 0 30px 30px 30px
  .agreement
    display flex
    justify-content center
    padding-right 20px
    .box
      //color $main_color
      font-size 20px
    .text
      line-height 42px
      margin-left -18px
      i
        color $main_color
        font-style normal
    .link
      line-height 42px
      margin-left 20px
      color red
  .line
    height 50px
    //background red
    border-bottom 1px solid #efefef
    margin-bottom 10px
    display flex
    padding-top 15px
    position relative
    &:last-child
      border none
    span
      width 50px
      //background red
      color $main_color
      font-size 20px
      padding-top 15px
    input
      flex 1
      //background black
      box-sizing border-box
      margin 10px 0
      &::placeholder
        color $shallow
    button
      width 100%
      height 45px
      border none
      //background url("../../../assets/images/line.png") repeat-y
      //background-size contain
      background $main_color
      color white
      font-weight 700
      border-radius 5px

    .verify
      //width 80px
      height 30px
      line-height 30px
      background $main_color
      border-radius 5px
      color white
      position absolute
      top 20px
      right 5px
      padding 0 10px
      &.send
        background $shallow
        color #333

.footer
  //background red
  text-align center
  li
    display inline-block
    width 100px
    height 16px
    line-height 16px
    //line-height 50px
    //box-sizing border-box
    border-right 1px solid $main_color
    &:last-child
      border none
</style>
